package com.leo.hbase.mapreduce.service;

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization CC
 * @website https://www.jlpyyf.com
 * @date 2019/11/13 10:31 下午
 * @since 1.0
 */
public abstract class ByteIterator implements Iterator<Byte> {
    @Override
    public abstract boolean hasNext();

    @Override
    public Byte next() {
        throw new UnsupportedOperationException();
    }

    public abstract byte nextByte();

    public int nextBuf(byte[] buf, int bufOff) {
        int sz = bufOff;
        while (sz < buf.length && hasNext()) {
            buf[sz] = nextByte();
            sz++;
        }
        return sz;
    }

    public abstract long bytesLeft();

    @Override
    public void remove() {
        throw new UnsupportedOperationException();
    }

    public void reset() {
        throw new UnsupportedOperationException();
    }

    @Override
    public String toString() {
        Charset charset = StandardCharsets.UTF_8;
        CharBuffer cb = charset.decode(ByteBuffer.wrap(this.toArray()));
        return cb.toString();
    }

    public byte[] toArray() {
        long left = bytesLeft();
        if (left != (int) left) {
            throw new ArrayIndexOutOfBoundsException("Too much data to fit in one array!");
        }
        byte[] ret = new byte[(int) left];
        int off = 0;
        while (off < ret.length) {
            off = nextBuf(ret, off);
        }
        return ret;
    }
}
